<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //构造函数
      function Person(name, age) {
        this.name = name;
        this.age = age;
        return 1;
      }
      Person.prototype.do = function () {
        console.log("do");
      };

      //实例化构造函数
      /* const p1 = new Person("xiaowang", 18);
      console.log(p1); */

      /*
        手动实现new

      */
      function myNew(constr, ...rest) {
        //1. new首先会创建一个对象,作为最后返回的实例化对象
        const obj = {};
        //2. 调用构造函数,并把构造函数的this指向obj对象,并拿到构造函数调用的返回值
        const result = constr.call(obj, ...rest);
        //3. 把创建的对象的隐式原型指向构造函数的原型对象
        obj.__proto__ = constr.prototype;

        //4. 判断构造函数的返回值是基本类型还是对象类型,如果是基本类型则直接返回obj,如果是对象类型则返回这个对象
        if (typeof result === "object" && result !== null) {
          return result;
        } else {
          return obj;
        }
      }

      const p1 = myNew(Person, "xiaowang", 10);
      console.log(p1, "p1");
    </script>
  </body>
</html>
